package cqrtplm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.ec.module.vo.ChgFormVO;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.iba.model.dto.SaveObjIBADTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.entity.RtChangeaffectFinishedbomDO;
import cqrtplm.mapper.RTChangeMapper;
import cqrtplm.mapper.RtChangeaffectFinishedbomMapper;
import cqrtplm.service.BatchUpdateDescriptionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BatchUpdateDescriptionServiceImpl implements BatchUpdateDescriptionService {
    private static final int MAX_RETRY = 150; //设置最大重试次数防止死循环
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private RTChangeMapper rtChangeMapper;
    @Resource
    private RtChangeaffectFinishedbomMapper rtChangeaffectFinishedbomMapper;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;

    public StringBuffer errMsg;

    /**
     * 批量修改物料描述
     *
     * @param workFlowContainerId
     * @return
     */
    @Transactional
    @Override
    public void batchUpdateDescription(String workFlowContainerId) {
        try {
            WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(new BigInteger(workFlowContainerId));
            if (!(workFlowContainerView instanceof FlowChgFormView)) {
                return;
            }
            errMsg = new StringBuffer();
            FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
            ChgFormVO chgFormVO = flowChgFormView.getChgFormVO();
            updateDesc(chgFormVO);
        } catch (Exception e) {
            log.error("批量更新物料描述异常", e);
            throw RTErrorCodeEnum.UPDATE_DESC_ERROR.getException(e.getMessage());
        }
    }

    //更新物料码描述
    public void updateDesc(ChgFormVO chgFormVO) throws Exception {
        String changeNo = chgFormVO.getObjectNumber();
        //受影响的成品BOM
        List<RtChangeaffectFinishedbomDO> rtChangeaffectFinishedbomDOS = this.rtChangeaffectFinishedbomMapper.queryByChangeNoAndPartNo(changeNo, "");
        //表单内容
        Map<String, List<Map<String, String>>> tempMap = new HashMap<>();
        List<SaveObjIBADTO> objWithIbaList = new ArrayList<>();
        String formData = chgFormVO.getFormData();
        if (StringUtils.isNotBlank(formData)) {
            JSONObject formDataJson = JSONObject.parseObject(formData);
            JSONArray subform47946 = formDataJson.getJSONArray("subform47946");
            if (CollectionUtils.isNotEmpty(subform47946)) {
                for (int i = 0; i < subform47946.size(); i++) {
                    String beforeChangeNo = subform47946.getJSONObject(i).getString("input67563");
                    String isUpdate = subform47946.getJSONObject(i).get("radio38347").toString();
                    if (StringUtils.isNotBlank(isUpdate) && isUpdate.contains(",")) {
                        isUpdate = isUpdate.split(",")[0];
                    }
                    String afterChangeNo = subform47946.getJSONObject(i).getString("radio73127");//radio73127
                    if (StringUtils.isNotBlank(afterChangeNo) && afterChangeNo.contains(",")) {
                        afterChangeNo = afterChangeNo.split(",")[0];
                    }
                    if ("是".equals(isUpdate)) {
                        if (CollectionUtils.isNotEmpty(rtChangeaffectFinishedbomDOS)) {
                            List<RtChangeaffectFinishedbomDO> finishBomList = rtChangeaffectFinishedbomDOS.stream().filter(item -> beforeChangeNo.equals(item.getPartnumber())).collect(Collectors.toList());
                            if (CollectionUtils.isNotEmpty(finishBomList)) {
                                for (RtChangeaffectFinishedbomDO item : finishBomList) {
                                    String materialCode = item.getMaterialcode();
                                    String colorCode = "";
                                    if ("H".equals(materialCode.charAt(5))) {
                                        colorCode = materialCode.split("-")[1];
                                    } else {
                                        colorCode = materialCode.split("-")[2];
                                    }
                                    materialCode = afterChangeNo + "-" + colorCode;
                                    JSONObject patternJson = rtChangeMapper.queryLatestMaterialByCode(afterChangeNo, RTPlmConstant.VIEW_DESIGN);
                                    JSONObject materialJson = rtChangeMapper.queryLatestMaterialByCode(materialCode, RTPlmConstant.VIEW_DESIGN);
                                    if (materialJson != null && patternJson != null) {
                                        buildSaveIbaDTO(objWithIbaList, patternJson, materialJson);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(objWithIbaList)) {
//                this.typlmAttributeValueService.batchSaveIBAByObjList(objWithIbaList, false);
                typlmAttributeValueService.batchSaveIBAByObjsNoConstraint(objWithIbaList, false);
            }
        }
    }

    public void buildSaveIbaDTO(List<SaveObjIBADTO> objWithIbaList, JSONObject patternJson, JSONObject materialJson) {
        //图样代号
        //Description 拼接描述
        //CompleteDescription 完整描述
        //物料
        //Description 物料码拼接描述
        //MaterialCodeDescription 物料码完整描述
        //PatternCodeDescription 图样代号描述
        //Common_Attributes|1757215074349 图样代号完整描述
        String patternId = patternJson.getString("OID");
        String patternType = patternJson.getString("OTYPE");
        String desc = rtChangeMapper.queryIBAValueByOidAndOtype(patternId, patternType, "Description");
        String completeDesc = rtChangeMapper.queryIBAValueByOidAndOtype(patternId, patternType, "CompleteDescription");
        String materialId = materialJson.getString("OID");
        String materialType = materialJson.getString("OTYPE");
        String materialDes = rtChangeMapper.queryIBAValueByOidAndOtype(materialId, materialType, "Description");
        String materialCompleteDesc = rtChangeMapper.queryIBAValueByOidAndOtype(materialId, materialType, "MaterialCodeDescription");
        if (StringUtils.isNotBlank(materialDes) && materialDes.contains(";")) {
            materialDes = desc + ";" + materialDes.split(";")[1];
        }
        if (StringUtils.isNotBlank(materialCompleteDesc) && materialCompleteDesc.contains(";")) {
            materialCompleteDesc = completeDesc + ";" + materialCompleteDesc.split(";")[1];
        }
        Map<String, List<String>> ibaAttributeMap = new HashMap<>();
        ibaAttributeMap.put("Description", Arrays.asList(materialDes));
        ibaAttributeMap.put("MaterialCodeDescription", Arrays.asList(materialCompleteDesc));
        ibaAttributeMap.put("PatternCodeDescription", Arrays.asList(desc));
        ibaAttributeMap.put("Common_Attributes|1757215074349", Arrays.asList(completeDesc));
        List<IbaDTO> objIbaList = buildSaveIbaDTO(ibaAttributeMap);
        SaveObjIBADTO saveObjIBADTO = new SaveObjIBADTO();
        CTyEntityBaseDO ctyEntityBaseDO = new CTyEntityBaseDO();
        ctyEntityBaseDO.setOid(materialId);
        ctyEntityBaseDO.setOtype(materialType);
        saveObjIBADTO.setCTyEntityBaseDO(ctyEntityBaseDO);
        saveObjIBADTO.setObjIbaList(objIbaList);
        objWithIbaList.add(saveObjIBADTO);
    }

    public List<IbaDTO> buildSaveIbaDTO(Map<String, List<String>> ibaMap) {
        List<IbaDTO> bomLinkIbaAttrs = new ArrayList<>();
        if (ibaMap != null) {
            for (String key : ibaMap.keySet()) {
                List<String> value = ibaMap.get(key);
                if (CollectionUtils.isNotEmpty(value)) {
                    IbaDTO ibadto = new IbaDTO();
                    ibadto.setKey(key);
                    ibadto.setValue(value.get(0));
                    bomLinkIbaAttrs.add(ibadto);
                }
            }
        }
        return bomLinkIbaAttrs;
    }
}
